/*
 * @Author: asushiye
 * @Date: 2020-07-03 08:51:09
 * @Commit: 微信公众号相关服务
 */
import { Inject, Injectable } from '@angular/core';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { TitleService, _HttpClient } from '@delon/theme';
import { Observable } from 'rxjs';

import { AfMessageService } from './af-message.service';
import { AfNavigationService } from './af-navigation.service';

@Injectable({
  providedIn: 'root'
})
export class AfWechatService {
  //启用微信图文系统- 公众号选择
  public startWechat: boolean = false;

  public wechatKey: any = '';
  public systemUrl: any = { account: '/wechat/account', home: '/home' };
  public wechatAccout: any = {
    selected: false,
    acount: {
      id: 'gh_9f8a77bd6148',
      name: 'timeslips测试公众号',
      wechatkey: 'test',
      remark: 'This is a test record and needs to be deleted',
      tokenLastMinute: 20,
      token: 'asushiye',
      enabled: true,
      logoUrl: ''
    }
  };

  constructor(
    private http: _HttpClient,
    private msg: AfMessageService,
    private nav: AfNavigationService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private titleServer: TitleService
  ) {}

  // 获取不同公众号访问基本路径，比如测试公众号的微服务 wechat-
  public getGatewayUrl(url: string) {
    return `api/wechat-${this.wechatKey}-news/${url}`;
  }

  // 从wechat-center 后台获取公众号账号信息
  public queryWechatAccount(wechatKey?: string): Observable<any> {
    const url = `api/wechat-center/wechat/account/simple/get?wechatKey=${wechatKey}`;
    return this.http.get(url);
  }

  // 微信公众号 - 缓存已选择公众号账号信息
  public setWechatAcount(wechat: any) {
    if (wechat) {
      this.wechatAccout.selected = true;
      this.wechatAccout.acount = wechat;
      this.wechatKey = this.wechatAccout.acount.wechatkey;
    }
  }

  // 快速导航 - 选择微信公众号页面
  public navigateToAccount() {
    this.nav.navigateByUrl(this.systemUrl.account);
    this.titleServer.setTitle('选择微信公众号');
    this.titleServer.setTitleByI18n('title.wechat.account');
  }

  // 快速导航 - 主页(默认页面)
  public navigateToHome() {
    this.nav.navigateByUrl(this.systemUrl.home);
  }

  // 身份认证后导航
  public navigateToLogin() {
    if (this.startWechat) {
      // 若是微信图文系统，则进入公众号选择页面
      this.tokenService.referrer!.url = this.systemUrl.account;
      this.navigateToAccount();
    } else {
      // 进入主页
      this.tokenService.referrer!.url = this.systemUrl.home;
      this.navigateToHome();
    }
  }
}
